import {
  CanActivate,
  ExecutionContext,
  HttpException,
  Injectable,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { PermissionKey } from 'src/decorator/custom.decorator';
import { UserService } from 'src/user/user.service';

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly userService: UserService,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const permission = this.reflector.get<string[]>(
      PermissionKey,
      context.getHandler(),
    );

    if (!permission) return true;

    const request: Request = context.switchToHttp().getRequest();

    const user = request.user;

    const rolesId = user.roles.map((role) => role.id);

    const res = await this.userService.getPermissionByRoleId(rolesId);

    console.log(res);
    console.log(permission);

    // 判断res中的权限是否包含permission中的权限，如果有一个不匹配的就抛出异常
    for (let i = 0; i < permission.length; i++) {
      if (!res.includes(permission[i])) {
        throw new HttpException('Permission denied', 403);
      }
    }

    return true;
  }
}
